<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_er_kami_buy extends discuz_table
{
    public function __construct()
    {
        $this->_table = 'er_kami_buy';
        $this->_pk = 'id';
        parent::__construct();
    }

    /**
     * 根据卡密查询
     * 
     * @param string $kami_key 卡密
     * @return array 卡密信息
     */
    public function fetch_by_code($kami_key) {
        return DB::fetch_first("SELECT * FROM %t WHERE kami_key=%s", array($this->_table, $kami_key));
    }

    /**
     * 根据分类id查询购买
     * 
     * @param array $kami_type_id 分类id
     * @return array 卡密
     */
    public function buy_kami_by_type_id($kami_type_id, $uid, $extcredits, $credit) {
        try {
            DB::query('START TRANSACTION');
            
            // 查询可用卡密
            $kami = DB::fetch_first("SELECT * FROM %t WHERE kami_type=%d AND status=1 AND (expire_time > %d OR expire_time = 0) LIMIT 1", 
                array($this->_table, $kami_type_id, TIMESTAMP));
            
            if(!$kami) {
                DB::query('ROLLBACK');
                // $log = '购买卡密失败：分类id'.$kami_type_id.'没有可用卡密'.("\n");
                // file_put_contents('kami_buy.log', $log, FILE_APPEND);
                return false;
            }
            
            // 更新卡密状态
            $update_data = array(
                'uid' => $uid,
                'status' => 2,
                'extcredits' => $extcredits,
                'credit' => $credit,
                'use_time' => TIMESTAMP
            );
            $result = $this->update($kami['id'], $update_data);
            
            if(!$result) {
                DB::query('ROLLBACK');
                return false;
            }
            
            DB::query('COMMIT');
            return $kami;
            
        } catch(Exception $e) {
            DB::query('ROLLBACK');
            // $log = '购买卡密失败：'.$e->getMessage()."\n";
            // file_put_contents('kami_buy.log', $log, FILE_APPEND);
            return false;
        }
    }

    /**
     * 获取卡密列表
     * @param int $page 页码
     * @param int $pagesize 每页数量
     * @param array $query 查询条件
     * @return array 卡密数组
     */
    public function fetch_all($page = 1, $pagesize = 10, $query = [], $expire_time = TIMESTAMP) {
        $where = array();
        $params = array($this->_table);

        if(!empty($query) && is_array($query)) {
            foreach($query as $key => $value) {
                $allowed_keys = ['id', 'uid','status', 'kami_key', 'kami_type'];
                if(!in_array($key, $allowed_keys)) {
                    continue;
                }
                if($value!== null && $value!== '' && $value!= 0) {
                    if(is_int($value) || ctype_digit($value)) {
                        $where[] = $key.'=%d';	
                    } else {
                        $where[] = $key.'=%s';	
                    }	
                    $params[] = $value;
                }
            } 	
        }

        if($expire_time > 0) {
            $where[] = '(expire_time IS NULL OR expire_time > %d OR expire_time = 0)';
            $params[] = $expire_time;
        }

        $count_sql = "SELECT COUNT(*) FROM %t";
		if(!empty($where)) {
			$count_sql .= " WHERE " . implode(' AND ', $where);
		}
		$total = DB::result_first($count_sql, $params);

        $sql = "SELECT * FROM %t";

        if(!empty($where)) {
			$sql .= " WHERE " . implode(' AND ', $where);
		}

        $sql .= " ORDER BY id DESC";

		$start = ($page - 1) * $pagesize;
        $limit_sql = " LIMIT $start, $pagesize";
		$sql.= $limit_sql;
		$data = DB::fetch_all($sql, $params);

		return array(
			'data' => $data,
			'total' => $total
		);
    }

    /**
     * 批量插入数据
     * @param array $data 数据数组
     * @return bool 插入成功返回true，失败返回false
     */
    public function insert_batch($data) {
        if(empty($data)) return false;
        
        $sql = "INSERT INTO ".DB::table($this->_table)." (uid, kami_key, kami_type, expire_time, create_time, update_time) VALUES ";
        $values = [];
        $params = [];

        foreach($data as $item) {
            $values[] = "(%d, %s, %d, %d, %d, %d)";
            $params[] = $item['uid'];
            $params[] = $item['kami_key'];
            $params[] = $item['kami_type'];
            $params[] = $item['expire_time'];
            $params[] = $item['create_time'];
            $params[] = $item['update_time'];
        }
        
        $sql .= implode(',', $values);
        return DB::query($sql, $params);
    }

    /**
     * 更新数据
     * @param int $id 数据id
     * @param array $data 更新数据
     * @return bool 更新成功返回true，失败返回false
     */
    public function update($id, $data, $unbuffered = false, $low_priority = false) {
        return DB::update($this->_table, $data, array('id' => $id), $unbuffered, $low_priority);	
    }

    /**
     * 删除数据
     * @param int $id 数据id
     * @return bool 删除成功返回true，失败返回false
     */
    public function delete($id, $unbuffered = false) {
        return DB::delete($this->_table, array('id' => $id), $unbuffered);
    }

    /**
     * 批量删除数据
     * @param array $ids 数据id数组
     * @return bool 删除成功返回true，失败返回false
     */
    public function delete_batch($ids, $unbuffered = false) {
        return DB::delete($this->_table, array('id' => $ids), $unbuffered);
    }

    /**
     * 根据卡密类型删除数据
     * @param int $kami_type 卡密类型
     * @return bool 删除成功返回true，失败返回false
     */
    public function delete_by_kami_type($kami_type) {
        return DB::delete($this->_table, array('kami_type' => $kami_type));
    }

    /**
     * 根据卡密列表获取已存在的卡密
     * @param array $kami_keys 卡密数组
     * @return array 已存在的卡密
     */
    public function fetch_all_by_kami_keys($kami_keys) {
        if(empty($kami_keys)) return [];
        
        $sql = "SELECT kami_key FROM %t WHERE kami_key IN (%n)";
        return DB::fetch_all($sql, [$this->_table, $kami_keys]);
    }
}
